<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="仓库名称">
							<uni-data-select
								v-model="searchModel.warehouseId"
								placeholder="请选择仓库名称"
								:localdata="allWarehouseList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="商品名称">
							<uni-easyinput v-model="searchModel.productName" placeholder="请输入商品名称" />
						</uni-forms-item>
						<uni-forms-item label="商品编码">
							<uni-easyinput v-model="searchModel.productCode" placeholder="请输入商品编码" />
						</uni-forms-item>
						<uni-forms-item label="开始时间">
							<uni-datetime-picker type="datetime" placeholder="请选择开始时间" v-model="searchModel.startTime"/>
						</uni-forms-item>
						<uni-forms-item label="结束时间">
							<uni-datetime-picker type="datetime" placeholder="请选择结束时间" v-model="searchModel.endTime"/>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
		</up-popup>
		<view class="content">
			<!--内容-->
			<view class="table">
				<ty-table
					:data="tableList"
					:columns="columns"
					:sortable="true"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:rowClassName="() => 'table-row'"
					stripe
					border>
					<template v-slot:before="{ row }">
						<view class="table-td-before table-cell table-td-row">
							<view class="table-td-row">
								仓库名称：
								<text class="table-td-text">{{row.warehouseName}}</text>
							</view>
							<view class="table-td-row">
								商品编码：
								<text class="table-td-text">{{row.productCode}}</text>
							</view>
							<view class="table-td-row">
								商品名称：
								<text class="table-td-text">{{row.productName}}</text>
							</view>
						</view>
					</template>
					<template v-slot:left="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								期初库存数量：
								<text class="table-td-text">{{row.startCount || 0}}</text>
							</view>
							<view class="table-td-row">
								采购入库数量：
								<text class="table-td-text">{{row.purchaseInCount || 0}}</text>
							</view>
							<view class="table-td-row">
								采购退货数量：
								<text class="table-td-text">{{row.purchaseReturnCount || 0}}</text>
							</view>
							
							<view class="table-td-row">
								调拨入库数量：
								<text class="table-td-text">{{row.allocationInCount || 0}}</text>
							</view>
							<view class="table-td-row">
								调拨出库数量：
								<text class="table-td-text">{{row.allocationOutCount || 0}}</text>
							</view>
							<view class="table-td-row">
								报损数量：
								<text class="table-td-text">{{row.destoryCount || 0}}</text>
							</view>
							<view class="table-td-row">
								报溢数量：
								<text class="table-td-text">{{row.overFlowCount || 0}}</text>
							</view>
							
							<view class="table-td-row">
								盘盈数量：
								<text class="table-td-text">{{row.stackInCount || 0}}</text>
							</view>
							<view class="table-td-row">
								盘亏数量：
								<text class="table-td-text">{{row.stackOutCount || 0}}</text>
							</view>
							<view class="table-td-row">
								销售数量：
								<text class="table-td-text">{{row.saleCount || 0}}</text>
							</view>
							<view class="table-td-row">
								期末库存数量：
								<text class="table-td-text">{{row.endCount || 0}}</text>
							</view>
							
						</view>
					</template>
					<template v-slot:right="{ row }">
						<view class="table-td-cell" v-if="checkPermi(['zhouyz:purchaseSaleStock:price'])">
							
							<view class="table-td-row">
								期初库存金额：
								<text class="table-td-text red">{{row.startMoney}}</text>
							</view>
							<view class="table-td-row">
								采购入库金额：
								<text class="table-td-text red">{{row.purchaseInMoney}}</text>
							</view>
							<view class="table-td-row">
								采购退货金额：
								<text class="table-td-text red">{{row.purchaseReturnMoney}}</text>
							</view>
							
							
							<view class="table-td-row">
								调拨入库金额：
								<text class="table-td-text red">{{row.allocationInMoney}}</text>
							</view>
							<view class="table-td-row">
								调拨出库金额：
								<text class="table-td-text red">{{row.allocationOutMoney}}</text>
							</view>
							<view class="table-td-row">
								报损金额：
								<text class="table-td-text red">{{row.destoryMoney}}</text>
							</view>
							<view class="table-td-row">
								报溢金额：
								<text class="table-td-text red">{{row.overFlowMoney}}</text>
							</view>
							
							<view class="table-td-row">
								盘盈金额：
								<text class="table-td-text red">{{row.stackInMoney}}</text>
							</view>
							<view class="table-td-row">
								盘亏金额：
								<text class="table-td-text red">{{row.stackOutMoney}}</text>
							</view>
							<view class="table-td-row">
								销售金额：
								<text class="table-td-text red">{{row.saleMoney}}</text>
							</view>
							<view class="table-td-row">
								期末库存金额：
								<text class="table-td-text red">{{row.endMoney}}</text>
							</view>
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table>
				<view class="table-total" v-if="tableList.length > 0">
					<view class="table-total-title">合计：</view>
					<view class="table-cell main-flex">
						<view class="table-td-cell">
							<view class="table-td-row">
								期初库存数量：
								<text class="table-td-text">{{totalData.startCount || 0}}</text>
							</view>
							<view class="table-td-row">
								采购入库数量：
								<text class="table-td-text">{{totalData.purchaseInCount || 0}}</text>
							</view>
							<view class="table-td-row">
								采购退货数量：
								<text class="table-td-text">{{totalData.purchaseReturnCount || 0}}</text>
							</view>
							<view class="table-td-row">
								调拨入库数量：
								<text class="table-td-text">{{totalData.allocationInCount || 0}}</text>
							</view>
							<view class="table-td-row">
								调拨出库数量：
								<text class="table-td-text">{{totalData.allocationOutCount || 0}}</text>
							</view>
							<view class="table-td-row">
								报损数量：
								<text class="table-td-text">{{totalData.destoryCount || 0}}</text>
							</view>
							<view class="table-td-row">
								报溢数量：
								<text class="table-td-text">{{totalData.overFlowCount || 0}}</text>
							</view>
							<view class="table-td-row">
								盘盈数量：
								<text class="table-td-text">{{totalData.stackInCount || 0}}</text>
							</view>
							<view class="table-td-row">
								盘亏数量：
								<text class="table-td-text">{{totalData.stackOutCount || 0}}</text>
							</view>
							<view class="table-td-row">
								销售数量：
								<text class="table-td-text">{{totalData.saleCount || 0}}</text>
							</view>
							<view class="table-td-row">
								期末库存数量：
								<text class="table-td-text">{{totalData.endCount || 0}}</text>
							</view>
						</view>
						
						<view class="table-td-cell" v-if="checkPermi(['zhouyz:purchaseSaleStock:price'])">
							<view class="table-td-row">
								期初库存金额：
								<text class="table-td-text red">{{totalData.startMoney}}</text>
							</view>
							<view class="table-td-row">
								采购入库金额：
								<text class="table-td-text red">{{totalData.purchaseInMoney}}</text>
							</view>
							<view class="table-td-row">
								采购退货金额：
								<text class="table-td-text red">{{totalData.purchaseReturnMoney}}</text>
							</view>
							<view class="table-td-row">
								调拨入库金额：
								<text class="table-td-text red">{{totalData.allocationInMoney}}</text>
							</view>
							<view class="table-td-row">
								调拨出库金额：
								<text class="table-td-text red">{{totalData.allocationOutMoney}}</text>
							</view>
							<view class="table-td-row">
								报损金额：
								<text class="table-td-text red">{{totalData.destoryMoney}}</text>
							</view>
							<view class="table-td-row">
								报溢金额：
								<text class="table-td-text red">{{totalData.overFlowMoney}}</text>
							</view>
							<view class="table-td-row">
								盘盈金额：
								<text class="table-td-text red">{{totalData.stackInMoney}}</text>
							</view>
							<view class="table-td-row">
								盘亏金额：
								<text class="table-td-text red">{{totalData.stackOutMoney}}</text>
							</view>
							<view class="table-td-row">
								销售金额：
								<text class="table-td-text red">{{totalData.saleMoney}}</text>
							</view>
							<view class="table-td-row">
								期末库存金额：
								<text class="table-td-text red">{{totalData.endMoney}}</text>
							</view>
						</view>
						
					</view>
				</view>
			</view>
			<!--统计图-->
			<!-- <view class="charts-box">
				<qiun-data-charts 
					type="column"
					:opts="opts"
					:chartData="chartData"
				/>
			</view> -->
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { allProvince } from "@/api/erp_api/region"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import qiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue'
import { warehouse } from "@/api/erp_api/warehouse"
import { purchaseSaleStock } from "@/api/erp_api/finance"
import { isObjectEmptySimple, copyText, arrText, getEdgeMonthFirstDay } from '@/utils/ty.js'
import useUserStore from '@/store/modules/user'
import { Decimal } from 'decimal.js'

	const userStore = useUserStore()

	// 标题设置
	const title = ref('')
	onLoad((option) => {
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
	})
	
	// 获取仓库
	const allWarehouseList = ref([])
	const getWarehouse = () => {
		warehouse().then(res => {
			allWarehouseList.value = res.rows.map(item => {
				return {
					...item,
					value: item.id,
					text: item.name
				}
			}) || []
		})
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		productName: '',
		startTime: `${uni.$u.timeFormat(new Date(), 'yyyy-mm-dd')} 00:00:00`,
		endTime: `${getEdgeMonthFirstDay(1)}`,
		productCode: '',
		warehouseId: ''
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			productName: '',
			startTime: `${uni.$u.timeFormat(new Date(), 'yyyy-mm-dd')} 00:00:00`,
			endTime: `${getEdgeMonthFirstDay(1)}`,
			productCode: '',
			warehouseId: ''
		}
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '数量', key: 'left' },
		{ title: '金额', key: 'right' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.productName) {
			params.productName = searchModel.value.productName
		}
		if (searchModel.value.startTime) {
			params.startTime = searchModel.value.startTime
		}
		if (searchModel.value.endTime) {
			params.endTime = searchModel.value.endTime
		}
		if (searchModel.value.productCode) {
			params.productCode = searchModel.value.productCode
		}
		if (searchModel.value.warehouseId) {
			params.warehouseId = searchModel.value.warehouseId
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		purchaseSaleStock(params).then(res => {
			tableList.value = res.data || []
			// getData()
			isLoading.value = false
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 合计
	const totalData = computed(() => {
		return {
			startCount: totalDataOne('startCount'),
			purchaseInCount: totalDataOne('purchaseInCount'),
			purchaseReturnCount: totalDataOne('purchaseReturnCount'),
			allocationInCount: totalDataOne('allocationInCount'),
			allocationOutCount: totalDataOne('allocationOutCount'),
			destoryCount: totalDataOne('destoryCount'),
			overFlowCount: totalDataOne('overFlowCount'),
			stackInCount: totalDataOne('stackInCount'),
			stackOutCount: totalDataOne('stackOutCount'),
			saleCount: totalDataOne('saleCount'),
			endCount: totalDataOne('endCount'),
			startMoney: totalDataOne('startMoney'),
			purchaseInMoney: totalDataOne('purchaseInMoney'),
			purchaseReturnMoney: totalDataOne('purchaseReturnMoney'),
			allocationInMoney: totalDataOne('allocationInMoney'),
			allocationOutMoney: totalDataOne('allocationOutMoney'),
			destoryMoney: totalDataOne('destoryMoney'),
			overFlowMoney: totalDataOne('overFlowMoney'),
			stackInMoney: totalDataOne('stackInMoney'),
			stackOutMoney: totalDataOne('stackOutMoney'),
			saleMoney: totalDataOne('saleMoney'),
			endMoney: totalDataOne('endMoney')
		}
	})
	
	const totalDataOne = (key) => {
		return tableList.value.reduce((prev, cur, index, arr)=> {
			return Decimal(prev).add(cur[key] ? cur[key] : 0).toNumber()
		}, 0)
	}
	
	const chartData = ref({})
	const opts = ref({
		color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
		padding: [15,15,0,5],
		touchMoveLimit: 24,
		legend: {},
		xAxis: {
			fontSize: 10,
			rotateLabel: true
		},
		yAxis: {
			data: [
				{
					min: 0
				}
			]
		},
		extra: {
			column: {
				type: "group",
				width: 10,
				activeBgColor: "#000000",
				activeBgOpacity: 0.08
			}
		}
	})
	
	const getData = () => {
		let res = {
			categories: [
				"期初库存",
				"采购入库",
				"采购退货",
				"调拨入库",
				"调拨出库",
				"报损",
				"报溢",
				"盘盈",
				"盘亏",
				"销售",
				"期末库存"
			],
			series: [
				{
					name: "数量",
					data: [
						totalDataOne('startCount'),
						totalDataOne('purchaseInCount'),
						totalDataOne('purchaseReturnCount'),
						totalDataOne('allocationInCount'),
						totalDataOne('allocationOutCount'),
						totalDataOne('destoryCount'),
						totalDataOne('overFlowCount'),
						totalDataOne('stackInCount'),
						totalDataOne('stackOutCount'),
						totalDataOne('saleCount'),
						totalDataOne('endCount')
					]
				},
				{
					name: "金额",
					data: [
						totalDataOne('startMoney'),
						totalDataOne('purchaseInMoney'),
						totalDataOne('purchaseReturnMoney'),
						totalDataOne('allocationInMoney'),
						totalDataOne('allocationOutMoney'),
						totalDataOne('destoryMoney'),
						totalDataOne('overFlowMoney'),
						totalDataOne('stackInMoney'),
						totalDataOne('stackOutMoney'),
						totalDataOne('saleMoney'),
						totalDataOne('endMoney')
					]
				}
			]
		}
		chartData.value = JSON.parse(JSON.stringify(res))
	}
 	const tap = (e) => {
		console.log(e)
	}
	onMounted(async () => {
		await getWarehouse()
		searchFirst()
	})
</script>

<style scoped lang="scss">
	.charts-box {
		position: relative;
		width: 100%;
		height: 300px;
		background-color: #ffffff;
		z-index: 999;
	}
</style>
